package com.xinggq.auth.service.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * Redis连接池监控定时任务
 * 定期检查Redis连接池状态
 *
 * @author xinggq
 * @since 2025-01-26
 */
@Slf4j
@Component
@ConditionalOnProperty(name = "redis.pool.monitor.enabled", havingValue = "true")
public class RedisPoolMonitorScheduler {

  private final RedisPoolMonitorConfig redisPoolMonitorConfig;

  public RedisPoolMonitorScheduler(RedisPoolMonitorConfig redisPoolMonitorConfig) {
    this.redisPoolMonitorConfig = redisPoolMonitorConfig;
  }

  /**
   * 每5分钟检查一次Redis连接状态
   */
  @Scheduled(fixedRate = 300000) // 5分钟
  public void checkRedisHealth() {
    try {
      boolean isHealthy = redisPoolMonitorConfig.checkRedisConnection();
      if (!isHealthy) {
        log.warn("Redis连接检查失败，请检查Redis服务状态");
      }
    } catch (Exception e) {
      log.error("Redis健康检查定时任务执行失败", e);
    }
  }

  /**
   * 每30分钟记录一次连接池状态
   */
  @Scheduled(fixedRate = 1800000) // 30分钟
  public void logPoolStatus() {
    try {
      redisPoolMonitorConfig.logPoolStatus();
      log.info("连接池信息: {}", redisPoolMonitorConfig.getPoolInfo());
    } catch (Exception e) {
      log.error("Redis连接池状态记录失败", e);
    }
  }
}